package files

import (
	"clouds.lgb24kcs.cn/controllers/files/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/oss"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type ObjectLists struct {
}

var ObjectListApi ObjectLists

func (l *ObjectLists) Lists(c *gin.Context, req request.ObjectAllReq, userId int64) {
	bucketInfo := models.Storage{}
	api := oss.OSS{}
	var count int64
	tx := global.APP.DB.Where("bucketname=? and userid=?", req.BucketName, userId).First(&bucketInfo)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ObjectList, tx.Error.Error())
	} else if tx.RowsAffected == 0 {
		global.APP.Log.Error(errors.New("数据加载失败").Error())
		utils.Fail(c, errorx.ObjectList, errors.New("数据加载失败").Error())
	} else {
		filesInfo := []models.Files{}
		svc := api.NewClient(bucketInfo.Accesskey, bucketInfo.Secretkey, bucketInfo.Zone)
		/*
			limit： 取多少条数据   10
			offset：从第几条数据开始查询 1
		*/
		scan := global.APP.DB.Raw("SELECT * FROM files WHERE user_id=? and root_dir=? and deleted_at IS NULL LIMIT ?,?", userId, req.CatalogueName, (req.Limit-1)*req.Page, req.Page).Scan(&filesInfo).Count(&count)
		if scan.Error != nil {
			global.APP.Log.Error(fmt.Sprintf("分页查询失败：%s", scan.Error.Error()))

			utils.Fail(c, errorx.ObjectList, errors.New("数据加载失败").Error())

		} else if tx.RowsAffected == 0 {
			global.APP.Log.Error(errors.New("数据加载失败").Error())
			utils.Fail(c, errorx.ObjectList, errors.New("数据加载失败").Error())
		} else {
			filesInfoResp := []request.ObjectAllResp{}
			for _, item := range filesInfo {
				itoa := strconv.Itoa(int(item.Size)) // 将size转为字符串类型
				// 检查文件是否存在
				if ok := api.CheckFileObject(svc, req.BucketName, req.CatalogueName+"/"+item.Filename); ok {
					filesInfoResp = append(filesInfoResp, request.ObjectAllResp{
						//Count:         count,
						FileLink:      item.FileLink,
						BucketName:    item.Bucketname,
						CatalogueName: item.RootDir,
						Type:          item.Type,
						ID:            int64(item.ID),
						UserId:        item.UserId,
						Size:          itoa,
						FileName:      item.Filename,
						CreateAt:      item.CreatedAt.Format(time.DateTime),
					})
				}

			}
			utils.Success(c, count, filesInfoResp)
		}
	}
}
